package com.thinkgem.jeesite.modules.sys.web;

import java.util.Collection;
import java.util.List;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.mapper.BeanMapper;
import com.thinkgem.jeesite.common.security.shiro.SessionVo;
import com.thinkgem.jeesite.common.security.shiro.ShrioConstants;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm.Principal;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 14-3-16
 * <p>Version: 1.0
 */

@Controller
@RequestMapping(value = "${adminPath}/sys/sessions")
public class SessionController extends BaseController{
	
	
    @Autowired
    private SessionDAO sessionDAO;
    
    @RequestMapping("")
    public String list(Model model) {
        Collection<Session> sessions =  sessionDAO.getActiveSessions();
        List<SessionVo> sessionVos = Lists.newArrayList();
        for (Session session : sessions) {
        	SessionVo destinationObject = new SessionVo();
        	BeanMapper.copy(session, destinationObject);
        	PrincipalCollection principalCollection =
                    (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if(principalCollection !=null){
            	Principal principal = (Principal)principalCollection.getPrimaryPrincipal();
            	destinationObject.setLoginname(principal.getLoginName());
            	destinationObject.setForceLogouted(session.getAttribute(ShrioConstants.SESSION_FORCE_LOGOUT_KEY) != null);
            }else{
            	continue;
            }
            sessionVos.add(destinationObject);
		}
        model.addAttribute("sessions", sessionVos);
        model.addAttribute("sessionCount", sessionVos.size());
        return "modules/sys/sessionList";
    }

    @RequestMapping("/{sessionId}/forceLogout")
    public String forceLogout(
            @PathVariable("sessionId") String sessionId, RedirectAttributes redirectAttributes) {
        try {
            Session session = sessionDAO.readSession(sessionId);
            if(session != null) {
                session.setAttribute(ShrioConstants.SESSION_FORCE_LOGOUT_KEY, Boolean.TRUE);
            }
        } catch (Exception e) {/*ignore*/}
        redirectAttributes.addFlashAttribute("msg", "强制退出成功！");
        return "redirect:"+adminPath + "/sys/sessions/";
    }

}